﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using NPOI.XSSF.UserModel;
using Org.BouncyCastle.Asn1.X509;
using RestSharp;
using SyncService.Abstractions.Events;
using SyncService.Abstractions.Services;
using System;
using System.Composition;
using System.Data;
using System.Security.AccessControl;
using System.Text.Json;
using System.Text.Json.Nodes;
using static Org.BouncyCastle.Bcpg.Attr.ImageAttrib;

namespace SyncService.Core.Services
{
    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "SapTransfer")]
    public class SapTransferService : AssetSyncServiceBase
    {
        private IMemoryCache? _cache = null;
        private ILogger<SapTransferService> _logger = null;
        private Dictionary<string, string> companyData = new Dictionary<string, string>();
        private Dictionary<string, string> centerData = new Dictionary<string, string>();
        private Dictionary<string, string> centerDatabyID = new Dictionary<string, string>();
        public SapTransferService() : base(YdConstants.YIDEA, "Sap", "")
        {
        }
        protected override void InitializeContext()
        {
            base.SetMultiCallback();
            base.InitializeContext();
            _cache = Resolver.Resolve<IMemoryCache>();
            _logger = Resolver.Resolve<ILogger<SapTransferService>>();
        }
        public override void ExecuteCore()
        {
            AssetSyncEvent Data = (AssetSyncEvent)State!;
            _logger.LogInformation("推sap进来了:" + Data.SourceType);

            if (Data.EventType == EventType.ReceiptEffect)
            {
                var serialNo = Data!.Data!["SerialNo"]!.ToString();
                string code = serialNo.Substring(0, 3);

                Thread.Sleep(60000);

                Transfer transfer = new Transfer();
                var formId = UserDefines.First(x => x.Name == "调拨自定义表单");
                var VformId = UserDefines.First(x => x.Name == "V测试资产调拨单");
                var VTestTransferTypeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
                var inComanyField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "调入公司码");
                var outComanyField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "调出公司码");
                var assetField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "资产列表");
                var assetVTestTableField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
                var assetAllotField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调拨状态");
                var assetVTestAllotField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试公司间调拨状态");
                switch (code)
                {

                    //批量调拨
                    case "TRA":
                        ExcuteTRA(Data);
                        //transfer.InCompanyCode = Data.Data![inComanyField.FieldId]?.ToString();
                        //transfer.OutCompanyCode = Data.Data[outComanyField.FieldId]?.ToString();

                        //transfer.ExtraData = new JsonObject
                        //{
                        //    ["SerialNo"] = Data.Data["SerialNo"]!.ToString(),
                        //    ["Memo"] = "",
                        //    ["type"] = "Trans",

                        //    ["ZDJBH"] = Data.Data["SerialNo"]!.ToString(),
                        //    ["FromId"] = Data.FormId.ToString()

                        //};

                        //transfer.Assets = GetPushAssets(Data, 49);
                        //if (transfer.Assets.Count > 0)
                        //{
                        //    ToClient.AddNewTransfer(transfer);
                        //}
                        //else
                        //{
                        //    var list = Data.Data![assetField.FieldId].AsArray();
                        //    foreach (var item in list)
                        //    {
                        //        item[assetAllotField.FieldId] = "调拨成功";
                        //    }
                        //    Data.Data![assetField.FieldId] = list;
                        //    var data2 = JsonSerializer.Serialize(Data.Data);
                        //    UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = Guid.Parse(Data.Data["Id"].ToString()), SerialNo = Data.Data["SerialNo"].ToString(), FormId = formId.Id, JsonData = data2 };
                        //    var updateResponse = YideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                        //}
                        break;
                    //新增调拨
                    case "NTR":
                        transfer.InCompanyCode = Data.Data![inComanyField.FieldId]?.ToString();
                        transfer.OutCompanyCode = Data.Data[outComanyField.FieldId]?.ToString();

                        transfer.ExtraData = new JsonObject
                        {
                            ["SerialNo"] = Data.Data["SerialNo"]!.ToString(),
                            ["Memo"] = "",
                            ["type"] = "Trans",

                            ["ZDJBH"] = Data.Data["SerialNo"]!.ToString(),
                            ["FromId"] = Data.FormId.ToString(),
                            ["Identification"] = 0
                        };

                        transfer.Assets = GetPushAssets(Data, 60);
                        if (transfer.Assets.Count > 0)
                        {


                            var flag = ToClient.AddNewTransfer(transfer);
                            var SapState = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "sap单据状态");
                            var condition = new JsonArray();
                            condition.Add(new JsonObject()
                            {
                                ["field"] = "serialNo",
                                ["type"] = "input",
                                ["label"] = "流水号",
                                ["opt"] = "Equal",
                                ["val"] = serialNo
                            });
                            CustomizedFormData order = new CustomizedFormData();
                            order = YideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();
                            var jsondata = JsonSerializer.Deserialize<JsonObject>(order.Data["dataJson"].ToString());
                            string message = string.Empty;
                            if (flag)
                            {
                                message = "SAP 已接收请求，待处理";
                                jsondata[SapState.FieldId] = message;
                                UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = order.Id, SerialNo = serialNo, FormId = VformId.Id, JsonData = JsonSerializer.Serialize(jsondata) };
                                var updateResponse = YideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                                if (updateResponse)
                                {
                                    _logger.LogInformation($"调拨单SerialNo：【{serialNo}】已成功发送至SAP，当前SAP推送状态修改为：{message}");
                                }
                                else
                                {
                                    _logger.LogInformation($"调拨单SerialNo：【{serialNo}】,修改SAP状态时,调用易点易动接口失败");
                                }


                            }
                            else
                            {
                                message = "SAP 未收到请求，请咨询客服处理";
                                jsondata[SapState.FieldId] = message;
                                UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = order.Id, SerialNo = serialNo, FormId = VformId.Id, JsonData = JsonSerializer.Serialize(jsondata) };
                                var updateResponse = YideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                                if (updateResponse)
                                {
                                    _logger.LogInformation($"调拨单SerialNo：【{serialNo}】未发送至SAP，当前SAP推送状态修改为：{message}");
                                }
                                else
                                {
                                    _logger.LogInformation($"调拨单SerialNo：【{serialNo}】未发送至SAP,修改SAP状态失败时,调用易点易动接口失败");
                                }

                            }
                        }
                        else
                        {
                            var count = 0;
                            var condition = new JsonArray();
                            condition.Add(new JsonObject()
                            {
                                ["field"] = "serialNo",
                                ["type"] = "input",
                                ["label"] = "流水号",
                                ["opt"] = "Equal",
                                ["val"] = Data.Data["SerialNo"]!.ToString()
                            });
                            CustomizedFormData order = new CustomizedFormData();
                            order = YideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();
                            var TransferType = Data.Data![VTestTransferTypeField.FieldId]["value"].ToString();
                            JsonArray assetList = new JsonArray();
                            if (TransferType == "公司内调拨")
                            {
                                assetList = Data.Data![assetField.FieldId].AsArray();
                                foreach (var item in assetList)
                                {
                                    item[assetAllotField.FieldId] = "调拨成功";
                                    count++;
                                }
                                Data.Data![assetField.FieldId] = assetList;
                            }
                            else
                            {
                                assetList = Data.Data![assetVTestTableField.FieldId].AsArray();
                                foreach (var item in assetList)
                                {
                                    item[assetVTestAllotField.FieldId] = "调拨成功";
                                    count++;
                                }
                                Data.Data![assetVTestTableField.FieldId] = assetList;
                            }

                            var data2 = JsonSerializer.Serialize(Data.Data);
                            UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = Guid.Parse(Data.Data["Id"].ToString()), SerialNo = Data.Data["SerialNo"].ToString(), FormId = VformId.Id, JsonData = data2 };
                            var updateResponse = YideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                            if (updateResponse)
                            {
                                if (count != 0 || count <= assetList.Count)
                                {
                                    var TuiKu = GenerateRefund(assetList, order, TransferType);
                                    if (TuiKu)
                                    {
                                        _logger.LogInformation("退库单生成成功");
                                    }
                                    else
                                    {
                                        _logger.LogInformation("退库单生成失败");
                                    }

                                    var LingYong = GenerateReceive(assetList, order, TransferType);
                                    if (LingYong)
                                    {
                                        _logger.LogInformation("领用单生成成功");
                                    }
                                    else
                                    {
                                        _logger.LogInformation("领用单生成失败");
                                    }
                                }
                                else
                                {
                                    _logger.LogInformation("该调拨单过账失败或者部分过账");
                                }
                            }
                        }
                        break;
                }
            }
        }
        public void ExcuteTRA(AssetSyncEvent Data)
        {
            var serialNo = Data.Data["SerialNo"].ToString();
            List<Asset> assets = new List<Asset>();
            DataTable dataTable = new DataTable();
            DataTable errorAsset = new DataTable();
            List<Asset> commonCompanyAsset = new List<Asset>();
            List<Asset> crossCompanyAsset = new List<Asset>();
            var company = UserDefines.First(x => x.Name == "公司主数据");
            var center = UserDefines.First(x => x.Name == "成本中心");
            var companyCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("公司代码"));
            var certerCompanyCodeField = ExtendFields.FirstOrDefault(s => s.ObjectType == 52 && s.Name.Equals("公司代码"));
            var shopCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺代码");
            var shopNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺名称");
            var assetComapnyField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("公司名称"));
            var companyMasterNameField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司名称");
            var fileUploadField = ExtendFields.Where(e => e.ObjectType == 59 && e.Name == "附件").FirstOrDefault();
            var fileDemain = ExtendFields.Where(e => e.ObjectType == 0 && e.Name == "附件域名").FirstOrDefault();
            var filePath = fileDemain.FieldId + Data.Data[fileUploadField.FieldId]?[0]["url"].ToString();
            var centerCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("成本中心码"));
            var centerNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心名");
            var assetCenterField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("成本中心名称"));
            var outCompanyCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name == "调出公司代码");
            var inCompanyCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name == "调入公司代码");
            var transferDateField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name == "调拨时间");


            var centerMasterNameField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心名称");
            var companyList = YideaClient.GetCustomizedFormDatas(formId: company.Id, new QueryParam() { }).ToList();
            ConvertCompanyToDic(companyList);
            var centerlist = YideaClient.GetCustomizedFormDatas(formId: center.Id, new QueryParam() { }).ToList();
            ConvertCenterToDic(centerlist);
            List<District> districts = YideaClient.GetDistricts(null).ToList();
            dataTable = Common.Excel.ReadExcel.ReadNetWorkFile(filePath);
            if (dataTable == null)
            {
                _logger.LogInformation("批量调拨单" + serialNo + "获取数据失败");
                return;
            }
            DataColumn workCol = dataTable.Columns.Add("失败原因", typeof(string));
            errorAsset = dataTable.Copy();
            errorAsset.Rows.Clear();

            List<string> barcodeList = new List<string>();
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                var row = dataTable.Rows[i];
                var barcode = row[0].ToString();
                barcodeList.Add(barcode);
            }

            #region    取所有资产
            var page = 0;
            var perPage = 100;
            var getAssetsBarcodes = barcodeList.Select(e => e).Skip(page * perPage).Take(perPage).ToList();
            while (getAssetsBarcodes.Any())
            {
                var yideaExistingAssetsRes = YideaClient.GetAssets(new QueryParam
                {
                    FilterString = $"orderby=-id&requireHierarchies=1&filterByPermission=1&barcodeIn={string.Join(",", getAssetsBarcodes)}"
                });
                var list = yideaExistingAssetsRes.ToList();
                assets.AddRange(list);
                page++;
                getAssetsBarcodes = barcodeList.Select(e => e).Skip(page * perPage).Take(perPage).ToList();

            }
            #endregion

            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                var row = dataTable.Rows[i];
                try
                {
                    // .1 资产编码
                    var barcode = row[0].ToString();
                    var asset = assets.Where(e => e.Barcode == barcode).FirstOrDefault();
                    var assetJson = JsonNode.Parse(asset.DataJson).AsObject();
                    var assetCompanyCode = assetJson[companyCodeField.FieldId].ToString();

                    // 2. 区域
                    var distrinct = row[1].ToString();
                    var districtID = districts.Where(e => e.Name == distrinct).FirstOrDefault();
                    asset.DistrictCode = districtID.Code;
                    asset.DistrictId = districtID.Id;
                    asset.DistrictName = districtID.Name;

                    // 3. 成本中心    
                    var centerCode = row[2].ToString();
                    string centerJson = string.Empty, companyJson = string.Empty, incompanyCode = "";
                    centerData.TryGetValue(centerCode, out centerJson);
                    var centerDataJson = JsonSerializer.Deserialize<JsonObject>(centerJson);
                    var centerDetail = JsonSerializer.Deserialize<JsonObject>(centerDataJson["dataJson"].ToString());
                    var centerName = centerDetail[centerMasterNameField.FieldId].ToString();
                    assetJson[centerCodeField.FieldId] = centerCode;
                    assetJson[centerNameField.FieldId] = (centerName.ToString());
                    centerData.Remove("dataJson");
                    assetJson[assetCenterField.FieldId] = centerDataJson;


                    // 4. 公司    根据成本中心公司代码找公司
                    string centerCompayCode = centerDetail[certerCompanyCodeField.FieldId].ToString();
                    companyData.TryGetValue(centerCompayCode, out companyJson);
                    var companyJsonData = JsonNode.Parse(companyJson).AsObject();
                    var companyDetail = JsonNode.Parse(companyJsonData["dataJson"].ToString()).AsObject();
                    incompanyCode = centerCompayCode;
                    assetJson[companyCodeField.FieldId] = centerCompayCode;
                    assetJson[assetComapnyField.FieldId] = companyDetail[companyMasterNameField.FieldId].ToString();
                    companyJsonData.Remove("dataJson");
                    assetJson[assetComapnyField.FieldId] = companyJsonData;

                    // .5 店铺
                    string centerId = "";
                    centerDatabyID.TryGetValue(centerCode, out centerId);
                    assetJson[shopCodeField.FieldId] = new JsonObject()
                    {
                        ["value"] = centerId,
                        ["label"] = centerCode,
                        ["color"] = new JsonObject()
                        {
                            ["backgroundColor"] = "#577eff",
                            ["foreColor"] = "#ffffff"
                        }
                    };
                    assetJson[shopNameField.FieldId] = centerName;
                    //实际存放地
                    //使用人名称
                    //使用人代码

                    assetJson[outCompanyCodeField.FieldId] = assetCompanyCode;
                    assetJson[inCompanyCodeField.FieldId] = incompanyCode;
                    assetJson[transferDateField.FieldId] = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                    asset.DataJson = JsonSerializer.Serialize(assetJson);
                    if (!IsPush(asset.AssetTypeCode))
                    {
                        try
                        {
                            YideaClient.UpdateAsset(asset, asset);
                            if (!string.IsNullOrEmpty(asset.ErrorMessage))
                            {
                                row[4] = asset.ErrorMessage;
                                errorAsset.ImportRow(row);
                                break;
                            }

                        }
                        catch (Exception ex)
                        {
                            row[4] = ex.ToString();
                            errorAsset.ImportRow(row);
                            break;

                        }
                        continue;
                    }

                    var facodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "财务资产编码");
                    if (string.IsNullOrEmpty(assetJson[facodeField.FieldId].ToString()))
                    {
                        row[4] = "该资产没有sap财务编码";
                        errorAsset.ImportRow(row);
                        continue;
                    }
                    if (assetCompanyCode == incompanyCode) //同公司调拨
                    {
                        _logger.LogInformation(serialNo + "步骤7");
                        commonCompanyAsset.Add(new Asset()
                        {
                            Barcode = asset.Barcode,
                            Name = asset.Name,
                            Specs = asset.Specs,
                            OwnCompanyCode = incompanyCode,
                            ExtraData = new JsonObject()
                            {
                                ["FACode"] = assetJson[facodeField.FieldId].ToString(),
                                ["CenterCode"] = assetJson[centerCodeField.FieldId].ToString()
                            }
                        });
                    }
                    else
                    {
                        _logger.LogInformation(serialNo + "步骤8");
                        //跨公司调拨
                        crossCompanyAsset.Add(new Asset()
                        {
                            Barcode = asset.Barcode,
                            Name = asset.Name,
                            Specs = asset.Specs,
                            AssetTypeCode = GetTopAssetTypeCode(asset.AssetTypeCode),
                            ExtraData = new JsonObject()
                            {
                                ["FACode"] = assetJson[facodeField.FieldId].ToString(),
                                ["CenterCode"] = assetJson[centerCodeField.FieldId].ToString(),
                                ["OutCompanyCode"] = assetCompanyCode,
                                ["InCompanyCode"] = incompanyCode
                            }
                        });
                    }

                }
                catch (Exception ex)
                {

                    _logger.LogInformation(serialNo + "发生异常：" + ex);
                    row[4] = "发生异常：" + ex.ToString();
                    errorAsset.ImportRow(row);
                    continue;
                }
            }
            bool flag = false;
            bool hasSuccess = false;  // 新增变量跟踪是否有成功的调用
            if (commonCompanyAsset.Count > 0)
            {
                Transfer transfer = new Transfer();
                transfer.InCompanyCode = "A";
                transfer.OutCompanyCode = "A";

                transfer.ExtraData = new JsonObject
                {
                    ["type"] = "mutiTrans",
                    ["SerialNo"] = Data.Data["SerialNo"]!.ToString(),
                    ["Memo"] = "",
                    ["ZDJBH"] = Data.Data["SerialNo"]!.ToString()

                };
                transfer.Assets = commonCompanyAsset;
                flag = ToClient.AddNewTransfer(transfer);
                if (flag) hasSuccess = true;  // 有一次成功就标记
                //如果通信成功  修改sap推送结果 
            }
            if (crossCompanyAsset.Count > 0)
            {
                Transfer transfer = new Transfer();
                transfer.InCompanyCode = "A";
                transfer.OutCompanyCode = "B";

                transfer.ExtraData = new JsonObject
                {
                    ["type"] = "mutiTrans",
                    ["SerialNo"] = Data.Data["SerialNo"]!.ToString(),
                    ["Memo"] = "",
                    ["ZDJBH"] = Data.Data["SerialNo"]!.ToString()
                };
                transfer.Assets = crossCompanyAsset;
                flag = ToClient.AddNewTransfer(transfer);
                if (flag) hasSuccess = true;  // 有一次成功就标记
                //如果通信成功  修改sap推送结果 
            }

            string fullFile = "";
            if (errorAsset.Rows.Count > 0)
            {
                var filepath = ExportToString(errorAsset);
                var domainNameField = ExtendFields.First(e => e.Name == "域名" && e.ObjectType == 0);
                fullFile = filepath == "" ? "" : domainNameField.FieldId + filepath;

            }
            // 最后根据实际情况判断
            string result = (commonCompanyAsset.Count > 0 || crossCompanyAsset.Count > 0)
                ? (hasSuccess ? "SAP 已接收请求，待处理" : "SAP 未收到请求，请咨询客服处理")
                : "没有资产可调用";

            WriteToForm(Data.Data["SerialNo"]!.ToString(), fullFile, result);

        }
        private void WriteToForm(string serialNo, string filePath, string sapResult)
        {
            _logger.LogInformation("批量调拨回写：" + serialNo);
            var form = UserDefines.Where(e => e.Name == "新资产批量调拨单").FirstOrDefault();
            var errorLinkField = ExtendFields.Where(e => e.Name == "错误数据链接" && e.ObjectType == 62).FirstOrDefault();
            var field = ExtendFields.First(x => x.ObjectType == 62 && x.Name == "SAP推送状态");
            var searchArray = new JsonArray();
            searchArray.Add(new JsonObject()
            {
                ["field"] = "serialNo",
                ["type"] = "input",
                ["label"] = "流水号",
                ["opt"] = "Equal",
                ["val"] = serialNo
            });

            var searchStr = JsonSerializer.Serialize(searchArray);
            var tj = YideaClient.GetUserDefinedForms(form.Id, new QueryParam() { FilterString = searchStr });
            if (tj.Count() > 0)
            {
                //var result = "成功";
                //if (!string.IsNullOrEmpty(filePath))
                //{
                //    result = "失败";
                //}
                var tjList = tj.ToList()[0];
                CustomizedFormData updateCustomer = new CustomizedFormData();
                updateCustomer.FormId = form.Id;
                updateCustomer.WebhookPush = false;
                updateCustomer.SerialNo = tjList.SerialNo;
                JsonObject upField = new JsonObject();
                upField[errorLinkField.FieldId] = new JsonObject
                {
                    ["value"] = filePath
                };
                upField[field.FieldId] = new JsonObject()
                {
                    ["value"] = sapResult
                };
                //upField[resultField.FieldId] = new JsonObject()
                //{
                //    ["value"] = result
                //};
                updateCustomer.Data = upField;
                var updateResponse1 = YideaClient.UpdateCustomizedFormData(updateCustomer, null);
                _logger.LogInformation("批量调拨回写：" + serialNo + "结果：" + updateResponse1);
            }
        }
        public string ExportToString(DataTable dataTable)
        {
            _logger.LogInformation("开始导出资产回写情况统计excel~");
            var template = Path.Combine(SyncService.Common.Constants.WebRootPath, "Templates", "批量调拨回写统计.xlsx");
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            var target = Path.Combine(SyncService.Common.Constants.WebRootPath, "temp", $"{fileName}批量调拨回写统计.xlsx");
            string directory = Path.GetDirectoryName(target);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            System.IO.File.Copy(template, target);
            FileStream file = new FileStream(target, FileMode.Open, FileAccess.Read);
            var workbook = new XSSFWorkbook(file);
            var sheet = workbook.GetSheet("批量调拨回写统计");
            int rowIndex = sheet.LastRowNum;

            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                var row = dataTable.Rows[i];
                XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
                dataRow.CreateCell(0).SetCellValue(row[0].ToString());
                dataRow.CreateCell(1).SetCellValue(row[1].ToString());
                dataRow.CreateCell(2).SetCellValue(row[2].ToString());
                dataRow.CreateCell(3).SetCellValue(row[3].ToString());
                dataRow.CreateCell(4).SetCellValue(row[4].ToString());
                ++rowIndex;
            }

            using (var stream = new FileStream(target, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(stream);
            }
            _logger.LogInformation("生成excel");
            _logger.LogInformation(target);
            return "/temp/" + fileName + "批量调拨回写统计.xlsx";
        }
        private void ConvertCompanyToDic(List<CustomizedFormData> datas)
        {
            var companyMasterCodeField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
            foreach (var data in datas)
            {
                var custmerData = JsonSerializer.Serialize(data.Data);
                JsonObject companyDataJson = JsonNode.Parse(data.Data["dataJson"].ToString()).AsObject();
                var key = companyDataJson[companyMasterCodeField.FieldId].ToString();
                if (companyData.ContainsKey(key))
                {
                    continue;
                }
                else
                {
                    companyData.Add(key, custmerData);
                }
            }
        }
        private void ConvertCenterToDic(List<CustomizedFormData> datas)
        {
            var centerMasterNameField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心名称");
            var centerMasterCodeField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
            foreach (var data in datas)
            {
                var custmerData = JsonSerializer.Serialize(data.Data);
                JsonObject companyDataJson = JsonNode.Parse(data.Data["dataJson"].ToString()).AsObject();
                var key = companyDataJson[centerMasterCodeField.FieldId].ToString();
                if (centerData.ContainsKey(key))
                {
                    continue;
                }
                else
                {
                    centerData.Add(key, custmerData);
                }
                if (centerDatabyID.ContainsKey(key))
                {
                    continue;
                }
                else
                {
                    centerDatabyID.Add(key, data.Id.ToString());
                }

            }
        }

        //调拨单回写SAP推送状态(值为data.Data)和明细
        public override void CallbackHander(CallbackData data)
        {
            _logger.LogInformation("开始修改");
            var condition = new JsonArray();
            condition.Add(new JsonObject()
            {
                ["field"] = "serialNo",
                ["type"] = "input",
                ["label"] = "流水号",
                ["opt"] = "Equal",
                ["val"] = data.DataKey
            });
            #region 字段
            //appsetting自定义字段
            var formId = UserDefines.First(x => x.Name == "调拨自定义表单");
            var assetTableField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "资产列表");
            var assetBarcodeField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "资产编码");
            var assetAllotField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "调拨状态");
            var assetSAPField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "sap单据状态");
            var assetTransferTypeField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "调拨类型");
            var assetQueryField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "资产列表query");

            //新调拨单自定义字段
            var VformId = UserDefines.First(x => x.Name == "V测试资产调拨单");
            //var VSAPformId = UserDefines.First(x => x.Name == "SAP字段更新");
            var assetTableField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表");
            var assetBarcodeField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产编码");
            var assetAllotField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调拨状态");
            var assetSAPField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "sap单据状态");
            var assetQueryField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表query");
            var CunFangDiField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "实际存放地");
            var QuBuField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入区部");
            var UserField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入使用人");

            var assetVTestTableField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
            var assetVTestBarcodeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产编码");
            var assetVTestAllotField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试公司间调拨状态");
            var VTestTransferTypeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
            var assetVTestQueryField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表query");
            var VTestCunFangDiField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试实际存放地");
            var VTestQuBuField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入区部");
            var VTestUserField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入使用人");

            #endregion
            var formIdZong = data.ExtraData["fromId"]!.ToString();
            CustomizedFormData order = new CustomizedFormData();
            var count = 0;
            //调拨表单
            if (formIdZong == formId.Id.ToString())
            {
                //获取自定义表单
                order = YideaClient.GetCustomizedFormDatas(formId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();
                JsonArray assetList = new JsonArray();
                var stringasd = "";
                if (order == null)
                {
                    Console.WriteLine("该单据不存在");
                }
                else
                {
                    var datajson = JsonNode.Parse(order.Data["dataJson"].ToString());
                    var TransferType = datajson[assetTransferTypeField.FieldId].ToString();
                    assetList = datajson[assetTableField.FieldId].AsArray();
                    if (TransferType == "0")
                    {
                        datajson[assetSAPField.FieldId] = data.Data;
                        stringasd = datajson[assetSAPField.FieldId].ToString();
                        var i = 0;
                        var WriteBackData = data.ExtraData["result"].AsArray();
                        foreach (var item in assetList)
                        {
                            var barcode = item[assetBarcodeField.FieldId].ToString();

                            var assetTypeCode = "";
                            if (item["assetTypeCode"] == null)
                            {
                                if (item[assetQueryField.FieldId]["assetTypeCode"] == null)
                                {
                                    var asset = YideaClient.GetAsset(barcode);
                                    if (asset != null)
                                    {
                                        assetTypeCode = asset.AssetTypeCode;
                                    }

                                }
                                else
                                {
                                    assetTypeCode = item[assetQueryField.FieldId]["assetTypeCode"].ToString();
                                }
                            }
                            else
                            {
                                assetTypeCode = item["assetTypeCode"].ToString();
                            }

                            if (IsPush(assetTypeCode))
                            {
                                var AssetCode = WriteBackData[i]["BarCode"].ToString();
                                var Sate = WriteBackData[i]["state"].ToString();
                                var message = WriteBackData[i]["reason"].ToString();
                                if (AssetCode == barcode && Sate == "S")
                                {
                                    item[assetAllotField.FieldId] = "调拨成功";
                                    count++;
                                }
                                else
                                {
                                    item[assetAllotField.FieldId] = "调拨失败：" + message;
                                }
                                i++;
                            }
                            else
                            {
                                item[assetAllotField.FieldId] = "调拨成功";
                                count++;
                            }
                            _logger.LogInformation("修改结果：" + item[assetAllotField.FieldId]);
                        }
                    }
                    else
                    {
                        datajson[assetSAPField.FieldId] = data.Data;
                        stringasd = datajson[assetSAPField.FieldId].ToString();
                        var i = 0;
                        var WriteBackData = data.ExtraData["result"].AsArray();
                        foreach (var item in assetList)
                        {
                            var barcode = item[assetBarcodeField.FieldId].ToString();

                            var assetTypeCode = "";
                            if (item["assetTypeCode"] == null)
                            {
                                if (item[assetQueryField.FieldId]["assetTypeCode"] == null)
                                {
                                    var asset = YideaClient.GetAsset(barcode);
                                    if (asset != null)
                                    {
                                        assetTypeCode = asset.AssetTypeCode;
                                    }

                                }
                                else
                                {
                                    assetTypeCode = item[assetQueryField.FieldId]["assetTypeCode"].ToString();
                                }
                            }
                            else
                            {
                                assetTypeCode = item["assetTypeCode"].ToString();
                            }

                            if (IsPush(assetTypeCode))
                            {
                                var Sate = WriteBackData[i]["TYPE"].ToString();
                                var message = WriteBackData[i]["MESSAGE"]?.ToString();
                                i++;
                                if (Sate == "S")
                                {
                                    item[assetAllotField.FieldId] = "调拨成功";

                                    var assetZiChan = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "财务资产编码");
                                    var assetjson = YideaClient.GetAsset(item[assetBarcodeField.FieldId].ToString());
                                    var asdsads = assetjson.DataJson;
                                    JsonObject keyValuePairs = (JsonObject)JsonObject.Parse(asdsads);
                                    keyValuePairs[assetZiChan.FieldId] = WriteBackData[i]["ANLN1_X"]?.ToString();
                                    assetjson.DataJson = JsonSerializer.Serialize(keyValuePairs);
                                    YideaClient.UpdateAsset(assetjson, assetjson);

                                    count++;
                                }
                                else
                                {
                                    item[assetAllotField.FieldId] = "调拨失败：" + message;
                                }
                            }
                            else
                            {
                                item[assetAllotField.FieldId] = "调拨成功";
                                count++;
                            }
                            _logger.LogInformation("修改结果：" + item[assetAllotField.FieldId]);
                        }
                    }

                    datajson[assetTableField.FieldId] = assetList;

                    var data2 = JsonSerializer.Serialize(datajson);
                    //获取自定义表单
                    UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = Guid.Parse(order.Data["id"].ToString()), SerialNo = order.Data["serialNo"].ToString(), FormId = formId.Id, JsonData = data2 };

                    var updateResponse = YideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                }
            }
            //新的调拨表单
            else if (formIdZong == VformId.Id.ToString())
            {
                //获取自定义表单
                order = YideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();
                JsonArray assetList = new JsonArray();
                var stringasd = "";
                if (order == null)
                {
                    Console.WriteLine("该单据不存在");
                }
                else
                {
                    //JsonObject newtable = new JsonObject();
                    var datajson = JsonNode.Parse(order.Data["dataJson"].ToString());
                    var TransferType = datajson[VTestTransferTypeField.FieldId]["value"].ToString();
                    if (TransferType == "公司内调拨")
                    {
                        assetList = datajson[assetTableField2.FieldId].AsArray();
                        datajson[assetSAPField2.FieldId] = data.Data;
                        stringasd = datajson[assetSAPField2.FieldId].ToString();
                        var i = 0;
                        var WriteBackData = data.ExtraData["result"].AsArray();
                        foreach (var item in assetList)
                        {
                            var barcode = item[assetBarcodeField2.FieldId].ToString();

                            var assetTypeCode = "";
                            if (item["assetTypeCode"] == null)
                            {
                                if (item[assetQueryField2.FieldId]["assetTypeCode"] == null)
                                {
                                    var asset = YideaClient.GetAsset(barcode);
                                    if (asset != null)
                                    {
                                        assetTypeCode = asset.AssetTypeCode;
                                    }

                                }
                                else
                                {
                                    assetTypeCode = item[assetQueryField2.FieldId]["assetTypeCode"].ToString();
                                }
                            }
                            else
                            {
                                assetTypeCode = item["assetTypeCode"].ToString();
                            }

                            if (IsPush(assetTypeCode))
                            {
                                //var FACodeCode = WriteBackData?[i]?["FACode"]?.ToString();
                                var AssetCode = WriteBackData[i]?["BarCode"]?.ToString();
                                var Sate = WriteBackData[i]?["state"]?.ToString();
                                var message = WriteBackData[i]?["reason"]?.ToString();
                                if (Sate == "S")
                                {
                                    item[assetAllotField2.FieldId] = "调拨成功";

                                    count++;
                                }
                                else
                                {
                                    item[assetAllotField2.FieldId] = "调拨失败：" + message;

                                }
                                i++;

                                //newtable.Add("input_1735611920986", AssetCode);
                                //newtable.Add("input_1735611668339", FACodeCode);
                                //newtable.Add("input_1735611669956", item[assetAllotField2.FieldId].ToString());
                                //var data3 = JsonSerializer.Serialize(newtable);
                                //UserDefinedForm NewDefinedForm = new UserDefinedForm() { FormId = VSAPformId.Id, JsonData = data3 };
                                //var addnew = YideaClient.AddNewUserDefinedForm(NewDefinedForm);
                                //if (addnew)
                                //{
                                //    newtable.Clear();
                                //}
                            }
                            else
                            {
                                item[assetAllotField2.FieldId] = "调拨成功";

                                count++;
                            }
                        }
                        datajson[assetTableField2.FieldId] = assetList;

                    }
                    else
                    {
                        datajson[assetSAPField2.FieldId] = data.Data;
                        stringasd = datajson[assetSAPField2.FieldId].ToString();
                        assetList = datajson[assetVTestTableField.FieldId].AsArray();
                        var i = 0;
                        var WriteBackData = data.ExtraData["result"].AsArray();
                        foreach (var item in assetList)
                        {
                            var barcode = item[assetVTestBarcodeField.FieldId].ToString();

                            var assetTypeCode = "";
                            if (item["assetTypeCode"] == null)
                            {
                                if (item[assetVTestQueryField.FieldId]["assetTypeCode"] == null)
                                {
                                    var asset = YideaClient.GetAsset(barcode);
                                    if (asset != null)
                                    {
                                        assetTypeCode = asset.AssetTypeCode;
                                    }

                                }
                                else
                                {
                                    assetTypeCode = item[assetVTestQueryField.FieldId]["assetTypeCode"].ToString();
                                }
                            }
                            else
                            {
                                assetTypeCode = item["assetTypeCode"].ToString();
                            }

                            if (IsPush(assetTypeCode))
                            {
                                var Sate = WriteBackData[i]["TYPE"].ToString();
                                var message = WriteBackData[i]["MESSAGE"]?.ToString();
                                var ANLN1 = WriteBackData[i]["ANLN1"]?.ToString();
                                if (Sate == "S")
                                {
                                    item[assetVTestAllotField.FieldId] = "调拨成功";

                                    var assetZiChan = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "财务资产编码");
                                    var assetjson = YideaClient.GetAsset(item[assetVTestBarcodeField.FieldId].ToString());
                                    var asdsads = assetjson.DataJson;
                                    JsonObject keyValuePairs = (JsonObject)JsonObject.Parse(asdsads);
                                    keyValuePairs[assetZiChan.FieldId] = WriteBackData[i]["ANLN1_X"]?.ToString();
                                    assetjson.DataJson = JsonSerializer.Serialize(keyValuePairs);
                                    YideaClient.UpdateAsset(assetjson, assetjson);

                                    count++;
                                }
                                else
                                {
                                    item[assetVTestAllotField.FieldId] = "调拨失败：" + message;
                                }
                                i++;
                                //newtable.Add("input_1735611920986", item[assetVTestBarcodeField.FieldId].ToString());
                                //newtable.Add("input_1735611668339", ANLN1);
                                //newtable.Add("input_1735611669956", item[assetAllotField2.FieldId].ToString());
                                //var data3 = JsonSerializer.Serialize(newtable);
                                //UserDefinedForm NewDefinedForm = new UserDefinedForm() { FormId = VSAPformId.Id, JsonData = data3 };
                                //var addnew = YideaClient.AddNewUserDefinedForm(NewDefinedForm);
                                //if (addnew)
                                //{
                                //    newtable.Clear();
                                //}
                            }
                            else
                            {
                                item[assetVTestAllotField.FieldId] = "调拨成功";
                                count++;
                            }
                        }
                        datajson[assetVTestTableField.FieldId] = assetList;
                    }

                    var data2 = JsonSerializer.Serialize(datajson);

                    //获取自定义表单
                    UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = Guid.Parse(order.Data["id"].ToString()), SerialNo = order.Data["serialNo"].ToString(), FormId = VformId.Id, JsonData = data2 };
                    _logger.LogInformation("参数" + data2);
                    var updateResponse = YideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                    _logger.LogInformation("修改结果" + updateResponse);
                    //生成退库单和领用单
                    if (updateResponse)
                    {
                        if (count != 0 || count <= assetList.Count)
                        {
                            var TuiKu = GenerateRefund(assetList, order, TransferType);
                            if (TuiKu)
                            {
                                _logger.LogInformation("退库单生成成功");
                            }
                            else
                            {
                                _logger.LogInformation("退库单生成失败");
                            }
                            var LingYong = GenerateReceive(assetList, order, TransferType);
                            if (LingYong)
                            {
                                _logger.LogInformation("领用单生成成功");
                            }
                            else
                            {
                                _logger.LogInformation("领用单生成失败");
                            }
                        }
                        else
                        {
                            _logger.LogInformation("该调拨单过账失败或者部分过账");
                        }
                    }
                }
            }
        }

        private List<Asset> GetPushAssets(AssetSyncEvent Data, int sourceType)
        {
            //int sourceType = Data.SourceType;
            var assetField = ExtendFields.First(x => x.ObjectType == sourceType && x.Name == "资产列表");
            var assetQueryField = ExtendFields.First(x => x.ObjectType == sourceType && x.Name == "资产列表query");
            var assetVTestField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
            var assetQueryVTestField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表query");
            var VTestTransferTypeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
            var formId = UserDefines.First(x => x.Name == "调拨自定义表单");
            var VformId = UserDefines.First(x => x.Name == "V测试资产调拨单");
            var pushAssets = new List<Asset>();
            //旧资产调拨
            if (Data.FormId.ToString() == formId.Id.ToString())
            {
                var list = Data.Data![assetField.FieldId].AsArray();
                foreach (var item in list)
                {
                    var barcode = item["barcode"] == null ? item[assetQueryField.FieldId]["barcode"]?.ToString() : item["barcode"]?.ToString();
                    var assetTypeCode = "";
                    if (item["assetTypeCode"] == null)
                    {
                        if (item[assetQueryField.FieldId]["assetTypeCode"] == null)
                        {
                            var asset = YideaClient.GetAsset(barcode);
                            if (asset != null)
                            {
                                assetTypeCode = asset.AssetTypeCode;
                            }

                        }
                        else
                        {
                            assetTypeCode = item[assetQueryField.FieldId]["assetTypeCode"].ToString();
                        }
                    }
                    else
                    {
                        assetTypeCode = item["assetTypeCode"].ToString();
                    }
                    if (sourceType == 50 || IsPush(assetTypeCode))
                    {

                        var facodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "财务资产编码");
                        var centerField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "调入成本中心码");
                        var centerField123 = ExtendFields.Where(x => x.ObjectType == 49);
                        var companyCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司代码");
                        var amountField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "不含税金额");
                        var taxAmountField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "税额");
                        var totalPriceAndTaxField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "价税合计");
                        var invoiceTypeCodeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "发票类型代码");
                        var taxCodeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "税码");
                        var assetCenterCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心代码");
                        var amount = 0.0M;
                        if (sourceType == 50)
                        {
                            var assetAmount = item[amountField.FieldId] == null ? item[assetQueryField.FieldId][amountField.FieldId]?.ToString() : item[amountField.FieldId]?.ToString();
                            decimal.TryParse(assetAmount, out amount);
                        }
                        var FACode = "";

                        if (item[facodeField.FieldId] != null || item[assetQueryField.FieldId][facodeField.FieldId] != null)
                        {
                            FACode = item[facodeField.FieldId] == null ? item[assetQueryField.FieldId][facodeField.FieldId]?.ToString() : item[facodeField.FieldId]?.ToString();

                        }
                        string spec = "";
                        if (item["specs"] != null || item[assetQueryField.FieldId]["specs"] != null)
                        {
                            spec = item["specs"] == null ? item[assetQueryField.FieldId]["specs"]?.ToString() : item["specs"]?.ToString();
                        }

                        var centercode = "";
                        if (item[assetCenterCodeField.FieldId] == null && item[assetQueryField.FieldId][assetCenterCodeField.FieldId] == null)
                        {
                            if (item["dataJson"] != null || item[assetQueryField.FieldId]["dataJson"] != null)
                            {
                                var assetDataJson = item["dataJson"] == null ? item[assetQueryField.FieldId]["dataJson"]?.ToString() : item["dataJson"]?.ToString();
                                var datajson = JsonNode.Parse(assetDataJson).AsObject();
                                centercode = datajson[assetCenterCodeField.FieldId]?.ToString();
                            }
                        }
                        else
                        {
                            centercode = item[assetCenterCodeField.FieldId] == null ? item[assetQueryField.FieldId][assetCenterCodeField.FieldId]?.ToString() : item[assetCenterCodeField.FieldId]?.ToString();
                        }

                        var assetName = item["name"] == null ? item[assetQueryField.FieldId]["name"]?.ToString() : item["name"]?.ToString();

                        var assetCenterCode = "";
                        var assetCompanyCode = "";
                        var assetTaxAmount = "";
                        var assetTotalPriceAndTax = "";
                        var assetInvoiceTypeCode = "";
                        var assetTaxCode = "";
                        if (sourceType == 50)
                        {
                            assetCenterCode = centercode;
                            assetTaxAmount = item[taxAmountField.FieldId] == null ? item[assetQueryField.FieldId][taxAmountField.FieldId]?.ToString() : item[taxAmountField.FieldId]?.ToString();
                            assetTotalPriceAndTax = item[totalPriceAndTaxField.FieldId] == null ? item[assetQueryField.FieldId][totalPriceAndTaxField.FieldId]?.ToString() : item[totalPriceAndTaxField.FieldId]?.ToString();
                            assetInvoiceTypeCode = item[invoiceTypeCodeField.FieldId] == null ? item[assetQueryField.FieldId][invoiceTypeCodeField.FieldId]?.ToString() : item[invoiceTypeCodeField.FieldId]?.ToString();
                            assetTaxCode = item[taxCodeField.FieldId] == null ? item[assetQueryField.FieldId][taxCodeField.FieldId]?.ToString() : item[taxCodeField.FieldId]?.ToString();
                        }
                        else if (sourceType == 49)
                        {
                            assetCenterCode = item[centerField.FieldId] == null ? item[assetQueryField.FieldId][centerField.FieldId]["label"]?.ToString() : item[centerField.FieldId]["label"]?.ToString();
                            assetCompanyCode = item[companyCodeField.FieldId] == null ? item[assetQueryField.FieldId][companyCodeField.FieldId]?.ToString() : item[companyCodeField.FieldId]?.ToString();
                        }
                        else
                        {
                            assetCompanyCode = item[companyCodeField.FieldId] == null ? item[assetQueryField.FieldId][companyCodeField.FieldId]?.ToString() : item[companyCodeField.FieldId]?.ToString();

                        }
                        pushAssets.Add(new Asset()
                        {

                            Barcode = barcode,
                            Name = assetName,
                            Specs = spec,
                            AssetTypeCode = GetTopAssetTypeCode(assetTypeCode),
                            Amount = amount,
                            ExtraData = new JsonObject
                            {
                                ["FACode"] = FACode,//sap资产编码
                                ["CenterCode"] = assetCenterCode,
                                ["CompanyCode"] = assetCompanyCode,
                                ["TaxAmount"] = assetTaxAmount,
                                ["TotalPriceAndTax"] = assetTotalPriceAndTax,
                                ["InvoiceTypeCode"] = assetInvoiceTypeCode,
                                ["TaxCode"] = assetTaxCode
                            }
                        });
                    }
                }
            }
            //新资产调拨
            if (Data.FormId.ToString() == VformId.Id.ToString())
            {
                if (Data.Data[VTestTransferTypeField.FieldId]["label"].ToString() == "公司内调拨")
                {
                    var list = Data.Data![assetField.FieldId].AsArray();
                    foreach (var item in list)
                    {
                        var barcode = item["barcode"] == null ? item[assetQueryField.FieldId]["barcode"]?.ToString() : item["barcode"]?.ToString();
                        var assetTypeCode = "";
                        if (item["assetTypeCode"] == null)
                        {
                            if (item[assetQueryField.FieldId]["assetTypeCode"] == null)
                            {
                                var asset = YideaClient.GetAsset(barcode);
                                if (asset != null)
                                {
                                    assetTypeCode = asset.AssetTypeCode;
                                }

                            }
                            else
                            {
                                assetTypeCode = item[assetQueryField.FieldId]["assetTypeCode"].ToString();
                            }
                        }
                        else
                        {
                            assetTypeCode = item["assetTypeCode"].ToString();
                        }
                        if (sourceType == 60 && IsPush(assetTypeCode))
                        {

                            var facodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "财务资产编码");
                            var centerField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入成本中心码");
                            var centerVTestField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入成本中心码");
                            var centerVTestJianField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试(公司间)调入成本中心码");
                            var companyCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司代码");
                            var amountField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "不含税金额");
                            var taxAmountField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "税额");
                            var totalPriceAndTaxField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "价税合计");
                            var invoiceTypeCodeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "发票类型代码");
                            var taxCodeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "税码");
                            var assetCenterCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心代码");
                            var amount = 0.0M;
                            if (sourceType == 60)
                            {
                                var assetAmount = item[amountField.FieldId] == null ? item[assetQueryField.FieldId][amountField.FieldId]?.ToString() : item[amountField.FieldId]?.ToString();
                                decimal.TryParse(assetAmount, out amount);
                            }
                            var FACode = "";

                            if (item[facodeField.FieldId] != null || item[assetQueryField.FieldId][facodeField.FieldId] != null)
                            {
                                FACode = item[facodeField.FieldId] == null ? item[assetQueryField.FieldId][facodeField.FieldId]?.ToString() : item[facodeField.FieldId]?.ToString();

                            }
                            string spec = "";
                            if (item["specs"] != null || item[assetQueryField.FieldId]["specs"] != null)
                            {
                                spec = item["specs"] == null ? item[assetQueryField.FieldId]["specs"]?.ToString() : item["specs"]?.ToString();
                            }

                            var centercode = "";
                            if (item[assetCenterCodeField.FieldId] == null && item[assetQueryField.FieldId][assetCenterCodeField.FieldId] == null)
                            {
                                if (item["dataJson"] != null || item[assetQueryField.FieldId]["dataJson"] != null)
                                {
                                    var assetDataJson = item["dataJson"] == null ? item[assetQueryField.FieldId]["dataJson"]?.ToString() : item["dataJson"]?.ToString();
                                    var datajson = JsonNode.Parse(assetDataJson).AsObject();
                                    centercode = datajson[assetCenterCodeField.FieldId]?.ToString();
                                }
                            }
                            else
                            {
                                centercode = item[assetCenterCodeField.FieldId] == null ? item[assetQueryField.FieldId][assetCenterCodeField.FieldId]?.ToString() : item[assetCenterCodeField.FieldId]?.ToString();
                            }

                            var assetName = item["name"] == null ? item[assetQueryField.FieldId]["name"]?.ToString() : item["name"]?.ToString();

                            var assetCenterCode = "";
                            var assetCompanyCode = "";
                            var assetTaxAmount = "";
                            var assetTotalPriceAndTax = "";
                            var assetInvoiceTypeCode = "";
                            var assetTaxCode = "";
                            if (sourceType == 50)
                            {
                                assetCenterCode = centercode;
                                assetTaxAmount = item[taxAmountField.FieldId] == null ? item[assetQueryField.FieldId][taxAmountField.FieldId]?.ToString() : item[taxAmountField.FieldId]?.ToString();
                                assetTotalPriceAndTax = item[totalPriceAndTaxField.FieldId] == null ? item[assetQueryField.FieldId][totalPriceAndTaxField.FieldId]?.ToString() : item[totalPriceAndTaxField.FieldId]?.ToString();
                                assetInvoiceTypeCode = item[invoiceTypeCodeField.FieldId] == null ? item[assetQueryField.FieldId][invoiceTypeCodeField.FieldId]?.ToString() : item[invoiceTypeCodeField.FieldId]?.ToString();
                                assetTaxCode = item[taxCodeField.FieldId] == null ? item[assetQueryField.FieldId][taxCodeField.FieldId]?.ToString() : item[taxCodeField.FieldId]?.ToString();
                            }
                            else if (sourceType == 60)
                            {
                                assetCenterCode = item[centerVTestField.FieldId].ToString();
                                assetCompanyCode = item[companyCodeField.FieldId] == null ? item[assetQueryField.FieldId][companyCodeField.FieldId]?.ToString() : item[companyCodeField.FieldId]?.ToString();
                            }
                            else
                            {
                                assetCompanyCode = item[companyCodeField.FieldId] == null ? item[assetQueryField.FieldId][companyCodeField.FieldId]?.ToString() : item[companyCodeField.FieldId]?.ToString();

                            }
                            pushAssets.Add(new Asset()
                            {

                                Barcode = barcode,
                                Name = assetName,
                                Specs = spec,
                                AssetTypeCode = GetTopAssetTypeCode(assetTypeCode),
                                Amount = amount,
                                ExtraData = new JsonObject
                                {
                                    ["FACode"] = FACode,//sap资产编码
                                    ["CenterCode"] = assetCenterCode,
                                    ["CompanyCode"] = assetCompanyCode,
                                    ["TaxAmount"] = assetTaxAmount,
                                    ["TotalPriceAndTax"] = assetTotalPriceAndTax,
                                    ["InvoiceTypeCode"] = assetInvoiceTypeCode,
                                    ["TaxCode"] = assetTaxCode
                                }
                            });
                        }
                    }
                }
                else
                {
                    var list = Data.Data![assetVTestField.FieldId].AsArray();
                    foreach (var item in list)
                    {
                        var barcode = item["barcode"] == null ? item[assetQueryVTestField.FieldId]["barcode"]?.ToString() : item["barcode"]?.ToString();
                        var assetTypeCode = "";
                        if (item["assetTypeCode"] == null)
                        {
                            if (item[assetQueryVTestField.FieldId]["assetTypeCode"] == null)
                            {
                                var asset = YideaClient.GetAsset(barcode);
                                if (asset != null)
                                {
                                    assetTypeCode = asset.AssetTypeCode;
                                }

                            }
                            else
                            {
                                assetTypeCode = item[assetQueryVTestField.FieldId]["assetTypeCode"].ToString();
                            }
                        }
                        else
                        {
                            assetTypeCode = item["assetTypeCode"].ToString();
                        }
                        if (sourceType == 60 && IsPush(assetTypeCode))
                        {

                            var facodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "财务资产编码");
                            var centerField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入成本中心码");
                            var centerVTestField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入成本中心码");
                            var centerVTestJianField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试(公司间)调入成本中心码");
                            var companyCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司代码");
                            var amountField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "不含税金额");
                            var taxAmountField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "税额");
                            var totalPriceAndTaxField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "价税合计");
                            var invoiceTypeCodeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "发票类型代码");
                            var taxCodeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "税码");
                            var assetCenterCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心代码");
                            var amount = 0.0M;
                            if (sourceType == 60)
                            {
                                var assetAmount = item[amountField.FieldId] == null ? item[assetQueryVTestField.FieldId][amountField.FieldId]?.ToString() : item[amountField.FieldId]?.ToString();
                                decimal.TryParse(assetAmount, out amount);
                            }
                            var FACode = "";

                            if (item[facodeField.FieldId] != null || item[assetQueryVTestField.FieldId][facodeField.FieldId] != null)
                            {
                                FACode = item[facodeField.FieldId] == null ? item[assetQueryVTestField.FieldId][facodeField.FieldId]?.ToString() : item[facodeField.FieldId]?.ToString();

                            }
                            string spec = "";
                            if (item["specs"] != null || item[assetQueryVTestField.FieldId]["specs"] != null)
                            {
                                spec = item["specs"] == null ? item[assetQueryVTestField.FieldId]["specs"]?.ToString() : item["specs"]?.ToString();
                            }

                            var centercode = "";
                            if (item[assetCenterCodeField.FieldId] == null && item[assetQueryVTestField.FieldId][assetCenterCodeField.FieldId] == null)
                            {
                                if (item["dataJson"] != null || item[assetQueryVTestField.FieldId]["dataJson"] != null)
                                {
                                    var assetDataJson = item["dataJson"] == null ? item[assetQueryVTestField.FieldId]["dataJson"]?.ToString() : item["dataJson"]?.ToString();
                                    var datajson = JsonNode.Parse(assetDataJson).AsObject();
                                    centercode = datajson[assetCenterCodeField.FieldId]?.ToString();
                                }
                            }
                            else
                            {
                                centercode = item[assetCenterCodeField.FieldId] == null ? item[assetQueryVTestField.FieldId][assetCenterCodeField.FieldId]?.ToString() : item[assetCenterCodeField.FieldId]?.ToString();
                            }

                            var assetName = item["name"] == null ? item[assetQueryVTestField.FieldId]["name"]?.ToString() : item["name"]?.ToString();

                            var assetCenterCode = "";
                            var assetCompanyCode = "";
                            var assetTaxAmount = "";
                            var assetTotalPriceAndTax = "";
                            var assetInvoiceTypeCode = "";
                            var assetTaxCode = "";
                            if (sourceType == 50)
                            {
                                assetCenterCode = centercode;
                                assetTaxAmount = item[taxAmountField.FieldId] == null ? item[assetQueryVTestField.FieldId][taxAmountField.FieldId]?.ToString() : item[taxAmountField.FieldId]?.ToString();
                                assetTotalPriceAndTax = item[totalPriceAndTaxField.FieldId] == null ? item[assetQueryVTestField.FieldId][totalPriceAndTaxField.FieldId]?.ToString() : item[totalPriceAndTaxField.FieldId]?.ToString();
                                assetInvoiceTypeCode = item[invoiceTypeCodeField.FieldId] == null ? item[assetQueryVTestField.FieldId][invoiceTypeCodeField.FieldId]?.ToString() : item[invoiceTypeCodeField.FieldId]?.ToString();
                                assetTaxCode = item[taxCodeField.FieldId] == null ? item[assetQueryVTestField.FieldId][taxCodeField.FieldId]?.ToString() : item[taxCodeField.FieldId]?.ToString();
                            }
                            else if (sourceType == 60)
                            {
                                if (Data.FormId.ToString() == formId.Id.ToString())
                                {
                                    assetCenterCode = item[centerField.FieldId] == null ? item[assetQueryVTestField.FieldId][centerField.FieldId]["label"]?.ToString() : item[centerField.FieldId]["label"]?.ToString();
                                    assetCompanyCode = item[companyCodeField.FieldId] == null ? item[assetQueryVTestField.FieldId][companyCodeField.FieldId]?.ToString() : item[companyCodeField.FieldId]?.ToString();
                                }
                                else if (Data.FormId.ToString() == VformId.Id.ToString())
                                {
                                    assetCenterCode = item[centerVTestJianField.FieldId].ToString();
                                    assetCompanyCode = item[companyCodeField.FieldId] == null ? item[assetQueryVTestField.FieldId][companyCodeField.FieldId]?.ToString() : item[companyCodeField.FieldId]?.ToString();
                                }

                            }
                            else
                            {
                                assetCompanyCode = item[companyCodeField.FieldId] == null ? item[assetQueryVTestField.FieldId][companyCodeField.FieldId]?.ToString() : item[companyCodeField.FieldId]?.ToString();

                            }
                            pushAssets.Add(new Asset()
                            {

                                Barcode = barcode,
                                Name = assetName,
                                Specs = spec,
                                AssetTypeCode = GetTopAssetTypeCode(assetTypeCode),
                                Amount = amount,
                                ExtraData = new JsonObject
                                {
                                    ["FACode"] = FACode,//sap资产编码
                                    ["CenterCode"] = assetCenterCode,
                                    ["CompanyCode"] = assetCompanyCode,
                                    ["TaxAmount"] = assetTaxAmount,
                                    ["TotalPriceAndTax"] = assetTotalPriceAndTax,
                                    ["InvoiceTypeCode"] = assetInvoiceTypeCode,
                                    ["TaxCode"] = assetTaxCode
                                }
                            });
                        }
                    }
                }
            }
            return pushAssets;
        }
        private bool IsPush(string assetTypeCode)
        {
            string NotPushSap = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "NotPushAssetType").FieldId;
            var code = GetTopAssetTypeCode(assetTypeCode);
            _logger.LogInformation("推送sap资产编码是否推送：" + NotPushSap.Contains("," + code + ","));
            return NotPushSap.Contains("," + code + ",");
        }
        private string GetTopAssetTypeCode(string assetTypeCode)
        {
            List<AssetType> assetTypeList = GetAssetTypeFromCache();
            var assetType = assetTypeList.Where(e => e.Code == assetTypeCode).FirstOrDefault();
            var hierarchyId = assetType.Hierarchy.Split('|')[0];
            int topAssetTypeId = 0;
            int.TryParse(hierarchyId, out topAssetTypeId);
            var topAssetType = assetTypeList.Where(e => e.Id == topAssetTypeId).FirstOrDefault();
            if (topAssetType != null)
            {
                return topAssetType.Code;
            }
            else
            {
                return assetTypeCode;
            }
        }
        private List<AssetType> GetAssetTypeFromCache()
        {
            _cache.TryGetValue("AssetType", out var assetValue);
            List<AssetType> assetTypeList = new List<AssetType>();
            if (assetValue != null)
            {
                assetTypeList = ((IEnumerable<dynamic>)assetValue).Select(item => new AssetType
                {
                    Id = item.Id,
                    Name = item.Name,
                    Hierarchy = item.Hierarchy,
                    Code = item.Code
                }).ToList();
            }
            else
            {
                assetTypeList = FromClient.GetAssetTypes(null).ToList();
                _cache.Set("AssetType", assetTypeList, DateTime.Now.AddMinutes(5));
            }
            return assetTypeList;
        }


        /// <summary>
        /// 生成领用单
        /// </summary>
        /// <returns></returns>
        private bool GenerateReceive(JsonArray assetList, CustomizedFormData order, string TransferType)
        {
            #region 字段
            //新调拨单自定义字段
            var LingYongformId = UserDefines.First(x => x.Name == "新资产领用单");
            var VformId = UserDefines.First(x => x.Name == "V测试资产调拨单");
            var lingCunField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "领用后实际存放地");
            var assetTableField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表");
            var assetBarcodeField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产编码");
            var assetAllotField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调拨状态");
            var assetSAPField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "sap单据状态");
            var assetQueryField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表query");
            var CunFangDiField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "实际存放地");
            var QuBuField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入区部");
            var UserField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入使用人");
            var ChengbenField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入成本中心码");

            var assetVTestTableField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
            var assetVTestBarcodeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产编码");
            var assetVTestAllotField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试公司间调拨状态");
            var VTestTransferTypeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
            var assetVTestQueryField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表query");
            var VTestCunFangDiField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试实际存放地");
            var VTestQuBuField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入区部");
            var VTestUserField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入使用人");
            var VTestChengBenField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试(公司间)调入成本中心码");


            var DrawAssetDate = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "资产详情");
            var DrawAssetDatequery = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "资产详情query");
            var DrawEmployee = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "员工选择");
            var DrawDepartment = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "部门选择");
            var DrawCunFang = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "存放地大类");
            var DrawDianPu = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "使用店铺");
            var DrawShiJi = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "实际存放地");
            var DrawWuLiu = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "物流信息");
            var DrawBeiZhu = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "备注");
            var DrawShiJiQuery = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "实际存放地query");
            var DrawChenBenCode = ExtendFields.First(x => x.ObjectType == 61 && x.Name == "成本中心代码");


            #endregion
            var btime = "";//修改时间
            JsonArray name = new JsonArray();
            btime = order.Data["modifiedTime"].ToString();
            JsonObject objTui = new JsonObject();
            JsonArray dataValue = new JsonArray();

            foreach (var item in assetList)
            {
                if (TransferType == "公司内调拨" && item[UserField2.FieldId] != null && item[assetAllotField2.FieldId].ToString() == "调拨成功")
                {
                    name.Add(JsonSerializer.Serialize(new { name = item[UserField2.FieldId]!["label"]!.ToString() + item[CunFangDiField2.FieldId]!.ToString() }));
                }
                else if (TransferType == "公司间调拨" && item[VTestUserField.FieldId] != null && item[assetVTestAllotField.FieldId].ToString() == "调拨成功")
                {
                    name.Add(JsonSerializer.Serialize(new { name = item[VTestUserField.FieldId]!["label"]!.ToString() + item[VTestCunFangDiField.FieldId]!.ToString() }));
                }
                else
                {
                    Dictionary<string, object> keys = new Dictionary<string, object>();
                    if (TransferType == "公司内调拨")
                    {
                        keys.Add("调拨方式", TransferType);
                        keys.Add("item[UserField2.FieldId]", item[UserField2.FieldId]);

                        keys.Add("调拨状态", item[assetAllotField2.FieldId].ToString());
                    }
                    if (TransferType == "公司间调拨")
                    {
                        keys.Add("调拨方式", TransferType);
                        keys.Add("item[VTestUserField.FieldId]", item[VTestUserField.FieldId]);
                        keys.Add("调拨状态", item[assetVTestAllotField.FieldId].ToString());
                    }
                    string erStr = JsonSerializer.Serialize(keys);
                    _logger.LogError($"生成自定义领用单--error TransferType:{TransferType}" + erStr);
                }
            }
            var deserializedArray = name.Select(token => JsonSerializer.Deserialize<JsonObject>(token.ToString())).ToList();
            // 使用Distinct方法去重，基于name属性定义去重规则
            var uniqueArray = deserializedArray.DistinctBy(jobject => jobject["name"].ToString()).ToList();
            // 将去重后的JObject列表重新序列化为JSON格式的JToken类型并放入新的JsonArray
            var resultArray = uniqueArray.Select(token => token).ToArray();
            bool ab = false;

            foreach (var item in resultArray)
            {
                var cunfang = "";
                var uservalue = "";//调入使用人value
                var userlabel = "";//调入使用人label
                var usercode = "";//调入使用人code
                var usertype = "";//调入使用人type
                var districtCode = "";//调入区部code
                var c = "";//实际存放地
                string departmentValue = string.Empty;//部门代码value
                var departmentCode = "";//部门代码code
                var departmentLabel = "";//部门代码label
                var departmentType = "";//部门代码type
                var selectcunfangvalue = "";//select实际存放地value
                var selectcunfanglabel = "";//select实际存放地label
                var selectCunDaLeivalue = "";//select存放地大类value
                var selectCunDaLeilabel = "";//select存放地大类label
                var shopName = string.Empty;//店铺名称
                var shopCode = string.Empty;//店铺代码
                var shopValue = string.Empty;//店铺id
                foreach (var itemasset in assetList)
                {
                    var a = "";
                    if (TransferType == "公司内调拨" && itemasset[UserField2.FieldId] != null && itemasset[assetAllotField2.FieldId].ToString() == "调拨成功")
                    {
                        a = itemasset[UserField2.FieldId]["label"]!.ToString() + itemasset[CunFangDiField2.FieldId]!.ToString();

                        var b = item["name"]!.ToString();
                        if (a == b)
                        {

                            JsonObject assetdatajsonling = new JsonObject();
                            assetdatajsonling.Add("id", itemasset["id"]!.GetValue<int>());
                            assetdatajsonling.Add("barcode", itemasset["barcode"]!.ToString());
                            assetdatajsonling.Add("name", itemasset["name"]!.ToString());
                            assetdatajsonling.Add("specs", itemasset["query_1690536112161"]?["specs"]?.ToString());
                            assetdatajsonling.Add("assetTypeName", itemasset["assetTypeName"]!.ToString());
                            //assetdatajsonling.Add("districtName", itemasset["districtName"]!.ToString());
                            assetdatajsonling.Add("select_1692243766053", new JsonObject
                            {
                                ["value"] = itemasset["select_1696820814413"]["value"].ToString(),
                                ["label"] = itemasset["select_1696820814413"]["label"].ToString(),
                                ["color"] = new JsonObject
                                {
                                    ["backgroundColor"] = "#52a8ff",
                                    ["foreColor"] = "#ffffff"
                                }
                            });
                            assetdatajsonling.Add(DrawChenBenCode.FieldId, itemasset[ChengbenField2.FieldId]!.ToString());
                            assetdatajsonling.Add("useCompanyName", itemasset["useCompanyName"]?.ToString());
                            JsonObject queryAble = new JsonObject
                            {
                                [DrawAssetDatequery.FieldId] = assetdatajsonling,
                                ["subId"] = itemasset["subId"]?.ToString(),
                                ["subIndex"] = itemasset["subIndex"].GetValue<int>(),
                                ["version"] = 2
                                //["subIndex"]

                            };

                            dataValue.Add(queryAble);
                            objTui[DrawAssetDate.FieldId] = dataValue;
                            c = itemasset[CunFangDiField2.FieldId]!.ToString();

                            districtCode = itemasset[QuBuField2.FieldId]["value"]!.ToString();
                            uservalue = itemasset["employeeSelect_1695217523213"]?["value"]?.ToString();
                            userlabel = itemasset["employeeSelect_1695217523213"]?["label"]?.ToString();
                            usercode = itemasset["employeeSelect_1695217523213"]?["code"]?.ToString();
                            usertype = itemasset["employeeSelect_1695217523213"]?["type"]?.ToString();
                            departmentValue = itemasset["departmentSelect_1699238334958"]?["value"]?.ToString() ?? string.Empty;
                            departmentCode = itemasset["departmentSelect_1699238334958"]?["code"]?.ToString() ?? string.Empty;
                            departmentLabel = itemasset["departmentSelect_1699238334958"]?["label"]?.ToString() ?? string.Empty;
                            departmentType = itemasset["departmentSelect_1699238334958"]?["type"]?.ToString() ?? string.Empty;
                            selectcunfangvalue = itemasset["select_1732633124408"]?["value"]?.ToString();
                            selectCunDaLeivalue = itemasset["select_1696820814413"]?["value"]?.ToString();
                            selectCunDaLeilabel = itemasset["select_1696820814413"]?["label"]?.ToString();
                            shopName = itemasset["input_1696820941201"]?.ToString() ?? string.Empty;
                            shopCode = itemasset["select_1696820861963"]?["label"]?.ToString() ?? string.Empty;
                            shopValue = itemasset["select_1696820861963"]?["value"]?.ToString() ?? string.Empty;


                        }
                    }
                    else if (TransferType == "公司间调拨" && itemasset[VTestUserField.FieldId] != null && itemasset[assetVTestAllotField.FieldId].ToString() == "调拨成功")
                    {
                        a = itemasset[VTestUserField.FieldId]["label"]!.ToString() + itemasset[VTestCunFangDiField.FieldId]!.ToString();

                        var b = item["name"]!.ToString();
                        if (a == b)
                        {
                            JsonObject assetdatajsonling = new JsonObject();
                            assetdatajsonling.Add("id", itemasset["id"]!.GetValue<int>());
                            assetdatajsonling.Add("barcode", itemasset["barcode"]!.ToString());//资产编码
                            assetdatajsonling.Add("name", itemasset["name"]!.ToString());//资产名称
                            assetdatajsonling.Add("specs", itemasset["specs"]?.ToString());//规格型号
                            assetdatajsonling.Add("assetTypeName", itemasset["assetTypeName"]!.ToString());//资产类别
                            assetdatajsonling.Add(DrawChenBenCode.FieldId, itemasset["input_1691661512030"]?.ToString());//调入成本中心代码
                            assetdatajsonling.Add("useCompanyName", itemasset["useCompanyName"]?.ToString());//使用公司                                         
                            JsonObject queryAble = new JsonObject
                            {
                                [DrawAssetDatequery.FieldId] = assetdatajsonling,
                                ["subId"] = itemasset["subId"]?.ToString(),
                                ["subIndex"] = itemasset["subIndex"].GetValue<int>(),
                                ["version"] = 2
                                //["subIndex"]

                            };

                            dataValue.Add(queryAble);
                            objTui[DrawAssetDate.FieldId] = dataValue;
                            c = itemasset["input_rousootb"]!.ToString();//实际存放地

                            districtCode = itemasset["districtSelect_x60b3v7s"]?["value"]!.ToString();//调入区部code
                            uservalue = itemasset["employeeSelect_dk9ny18k"]?["value"]?.ToString();//使用人value
                            userlabel = itemasset["employeeSelect_dk9ny18k"]?["label"]?.ToString();//使用人label
                            usercode = itemasset["employeeSelect_dk9ny18k"]?["code"]?.ToString();//使用人code
                            usertype = itemasset["employeeSelect_dk9ny18k"]?["type"]?.ToString();//使用人type
                            departmentValue = itemasset["departmentSelect_2t6gk02j"]?["value"]?.ToString() ?? string.Empty;//调入部门value
                            departmentCode = itemasset["departmentSelect_2t6gk02j"]?["code"]?.ToString() ?? string.Empty;//调入部们code
                            departmentLabel = itemasset["departmentSelect_2t6gk02j"]?["label"]?.ToString() ?? string.Empty;//调入部门label
                            departmentType = itemasset["departmentSelect_2t6gk02j"]?["type"]?.ToString() ?? string.Empty;//调入部门type
                                                                                                                         //selectcunfangvalue = itemasset[""]["value"].ToString();

                            selectCunDaLeivalue = itemasset["select_kddqvnb8"]?["value"]?.ToString();
                            selectCunDaLeilabel = itemasset["select_kddqvnb8"]?["label"]?.ToString();
                            selectcunfanglabel = itemasset["input_rousootb"]?.ToString();
                            shopName = itemasset["input_hdjpkhne"]?.ToString() ?? string.Empty;
                            shopCode = itemasset["select_li74i42i"]?["label"]?.ToString() ?? string.Empty;
                            shopValue = itemasset["select_li74i42i"]?["value"]?.ToString() ?? string.Empty;
                        }
                    }
                }

                var opoiubhnij = 11111;
                objTui[DrawShiJi.FieldId] = c;
                objTui[DrawBeiZhu.FieldId] = "本单由调拨单号（" + order.Data["SerialNo"] + "）自动生成";
                objTui[DrawWuLiu.FieldId] = new JsonObject
                {
                    ["value"] = "03",
                    ["label"] = "物流/快递",
                    ["color"] = new JsonObject
                    {
                        ["backgroundColor"] = "#577eff",
                        ["foreColor"] = "#ffffff"
                    }
                };
                objTui[DrawEmployee.FieldId] = new JsonObject
                {
                    ["value"] = uservalue,
                    ["label"] = userlabel,
                    ["code"] = usercode,
                    ["type"] = usertype
                };
                objTui[DrawDepartment.FieldId] = new JsonObject
                {
                    ["value"] = departmentValue,
                    ["label"] = departmentLabel,
                    ["code"] = departmentCode,
                    ["type"] = departmentType
                };

                objTui[DrawCunFang.FieldId] = new JsonObject
                {
                    ["value"] = selectCunDaLeivalue,
                    ["label"] = selectCunDaLeilabel,
                    ["color"] = new JsonObject
                    {
                        ["backgroundColor"] = "#577eff",
                        ["foreColor"] = "#ffffff"
                    }
                };

                //if (TransferType == "公司内调拨")
                //{
                //    objTui[DrawDianPu.FieldId] = new JsonObject
                //    {
                //        ["value"] = selectcunfangvalue,
                //        ["label"] = selectcunfanglabel,
                //        ["color"] = new JsonObject
                //        {
                //            ["backgroundColor"] = "#52a8ff",
                //            ["foreColor"] = "#ffffff"
                //        }
                //    };
                //}
                //else
                //{
                //    objTui[DrawDianPu.FieldId] = selectcunfanglabel;
                //}
                objTui["input_1747725516998"] = shopName;
                objTui["input_1747725500531"] = shopCode;
                objTui["select_1744616605684"] = new JsonObject
                {
                    ["value"] = shopValue,
                    ["label"] = shopCode + " " + shopName,
                    ["color"] = new JsonObject
                    {
                        ["backgroundColor"] = "#52a8ff",
                        ["foreColor"] = "#ffffff"
                    }
                };
                objTui["version"] = "";


                var jsss = JsonSerializer.Serialize(objTui).ToString();

                UserDefinedForm NewDefinedForm = new UserDefinedForm() { FormId = LingYongformId.Id, JsonData = JsonSerializer.Serialize(objTui) };

                if (name.Count == 0)
                {

                    objTui.Clear();
                    dataValue.Clear();
                }
                else
                {
                    ab = YideaClient.AddNewUserDefinedForm(NewDefinedForm);
                    if (ab)
                    {
                        _logger.LogInformation("领用单生成成功");
                        objTui.Clear();
                        dataValue.Clear();
                    }
                    else
                    {
                        _logger.LogInformation("领用单生成失败");
                        objTui.Clear();
                        dataValue.Clear();
                    }

                }
            }

            return ab;
        }


        /// <summary>
        /// 生成退库单
        /// </summary>
        /// <returns></returns>
        private bool GenerateRefund(JsonArray assetList, CustomizedFormData order, string TransferType)
        {
            #region 字段
            //新调拨单自定义字段
            var VformId = UserDefines.First(x => x.Name == "V测试资产调拨单");
            var vsss = UserDefines.First(x => x.Name == "测试退库自定义表单");

            var cunfang1 = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "存放地");
            var useDepart = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "使用部门");
            var shopCode = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺代码");
            var shopName = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺名称");
            var addressBig = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "存放地大类");
            var TuiKuField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "退库后实际存放地");
            var assetTableField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表");
            var assetBarcodeField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产编码");
            var assetAllotField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调拨状态");
            var assetSAPField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "sap单据状态");
            var assetQueryField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表query");
            var CunFangDiField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "实际存放地");
            var QuBuField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入区部");
            var UserField2 = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "调入使用人");


            var assetVTestTableField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
            var assetVTestBarcodeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产编码");
            var assetVTestAllotField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试公司间调拨状态");
            var VTestTransferTypeField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
            var assetVTestQueryField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表query");
            var VTestCunFangDiField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试实际存放地");
            var VTestQuBuField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入区部");
            var VTestUserField = ExtendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入使用人");


            //自定义资产退库单
            var customBigcun = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "存放地大类");
            var customCunFang = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "实际存放地");
            var customTuiKu = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "退库配送方式");
            var customAssetdetails = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "资产详情");
            var customAssetList = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "资产列表");
            var customCategory = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "调入存放地大类");
            var remarks = ExtendFields.First(x => x.ObjectType == 70 && x.Name == "退库单备注");

            #endregion

            var btime = "";
            Order OrderJson = new Order();

            btime = order.Data["modifiedTime"].ToString();

            var addressdate = string.Empty;
            var districtCodedate = string.Empty;
            bool qwe = false;

            JsonArray CunFang = new JsonArray();
            JsonObject objTui = new JsonObject();
            JsonArray dataValue = new JsonArray();


            foreach (var item in assetList)
            {
                if (TransferType == "公司内调拨" && item[CunFangDiField2.FieldId] != null && item[assetAllotField2.FieldId].ToString() == "调拨成功")
                {
                    CunFang.Add(JsonSerializer.Serialize(new { CunFang = item[CunFangDiField2.FieldId]!.ToString() }));
                }
                else if (TransferType == "公司间调拨" && item[VTestCunFangDiField.FieldId] != null && item[assetVTestAllotField.FieldId].ToString() == "调拨成功")
                {
                    CunFang.Add(JsonSerializer.Serialize(new { CunFang = item[VTestCunFangDiField.FieldId]!.ToString() }));
                }
                else
                {
                    string str = string.Empty;
                    if (TransferType == "公司内调拨")
                    {
                        str = $"调拨方式:" + TransferType + "，存放地：" + item[CunFangDiField2.FieldId].ToString() + "，调拨状态:" + item[assetAllotField2.FieldId].ToString();
                    }
                    else
                    {
                        str = $"调拨方式:" + TransferType + "，存放地：" + item[VTestCunFangDiField.FieldId].ToString() + "，调拨状态:" + item[assetVTestAllotField.FieldId].ToString();
                    }
                    _logger.LogError($"生成自定义退库单error-——：{str}");
                }


            }



            var deserializedArray = CunFang.Select(token => JsonSerializer.Deserialize<JsonObject>(token.ToString())).ToList();
            // 使用Distinct方法去重，基于name属性定义去重规则
            var uniqueArray = deserializedArray.DistinctBy(jobject => jobject["CunFang"].ToString()).ToList();
            // 将去重后的JObject列表重新序列化为JSON格式的JToken类型并放入新的JsonArray
            var resultArray = uniqueArray.Select(token => token).ToArray();
            var asd = "";
            foreach (var itemqwe in resultArray)
            {
                foreach (var item in assetList)
                {
                    var a = "";
                    if (TransferType == "公司内调拨" && item[assetAllotField2.FieldId].ToString() == "调拨成功")
                    {
                        a = item[CunFangDiField2.FieldId]!.ToString();

                        asd = CunFangDiField2.FieldId;

                        var b = itemqwe["CunFang"]!.ToString();
                        if (a == b)
                        {
                            var assetfrist = YideaClient.GetAsset(item[assetBarcodeField2.FieldId]?.ToString());
                            var asdsads = assetfrist.ManagerEmployeeName;
                            var sadwerq = assetfrist.ManagerEmployeeName;
                            var sate = assetfrist.State;
                            var user = assetfrist.User;
                            addressdate = item[CunFangDiField2.FieldId]!.ToString();
                            districtCodedate = item[QuBuField2.FieldId]["label"]!.ToString();
                            //if (sate == 1 && user != null)
                            //{
                            JsonObject query = new JsonObject()

                            {
                                ["id"] = item["id"]?.GetValue<int>(),
                                //资产编码
                                ["barcode"] = item["barcode"]!.ToString(),
                                //资产名称
                                ["name"] = item[assetQueryField2.FieldId]?["name"]?.ToString(),
                                //使用人
                                ["user"] = item[UserField2.FieldId]?["label"]?.ToString(),
                                //使用部门
                                ["useDepartmentName"] = item[useDepart.FieldId]?["label"]?.ToString() ?? string.Empty,
                                //资产存放地大类                                                                     
                                [addressBig.FieldId] = new JsonObject
                                {
                                    ["value"] = item[customCategory.FieldId]?["value"]?.ToString(),
                                    ["label"] = item[customCategory.FieldId]?["label"]?.ToString(),
                                },
                                //实际存放地
                                [cunfang1.FieldId] = item[CunFangDiField2.FieldId]?.ToString(),
                                //店铺名称
                                [shopName.FieldId] = item[shopName.FieldId]?.ToString() ?? string.Empty,
                                //店铺代码
                                [shopCode.FieldId] = new JsonObject
                                {
                                    ["value"] = item[shopCode.FieldId]?["value"]?.ToString(),
                                    ["label"] = item[shopCode.FieldId]?["label"]?.ToString(),
                                }
                            };
                            objTui[customAssetdetails.FieldId] = dataValue;
                            dataValue.Add(new JsonObject { [customAssetList.FieldId] = query });
                            //退库配送方式 
                            objTui[customTuiKu.FieldId] = new JsonObject
                            {
                                ["value"] = "03",
                                ["label"] = "物流/快递",
                            };
                            //存放地大类
                            objTui[customBigcun.FieldId] = new JsonObject
                            {
                                ["value"] = item[customCategory.FieldId]?["value"]?.ToString(),
                                ["label"] = item[customCategory.FieldId]?["label"]?.ToString(),
                            };
                            //实际存放地
                            objTui[customCunFang.FieldId] = item[CunFangDiField2.FieldId]?.ToString();



                            //}
                        }
                    }
                    else if (TransferType == "公司间调拨" && item[assetVTestAllotField.FieldId].ToString() == "调拨成功")
                    {
                        a = item[VTestCunFangDiField.FieldId]!.ToString();

                        asd = VTestCunFangDiField.FieldId;

                        var b = itemqwe["CunFang"]!.ToString();
                        if (a == b)
                        {
                            var assetfrist = YideaClient.GetAsset(item[assetVTestBarcodeField.FieldId].ToString());
                            var asdsads = assetfrist.ManagerEmployeeName;
                            var sadwerq = assetfrist.ManagerEmployeeName;
                            var sate = assetfrist.State;
                            var user = assetfrist.User;
                            if (sate == 1 && user != null)
                            {

                                JsonObject query = new JsonObject()

                                {
                                    ["id"] = item["id"]?.GetValue<int>(),
                                    //资产编码
                                    ["barcode"] = item["barcode"]!.ToString(),
                                    //资产名称
                                    ["name"] = item["name"]?.ToString(),
                                    //使用人
                                    ["user"] = item["employeeSelect_dk9ny18k"]?["label"]?.ToString(),
                                    //使用部门
                                    ["useDepartmentName"] = item["departmentSelect_2t6gk02j"]?["label"]?.ToString() ?? string.Empty,
                                    //资产存放地大类                                                                     
                                    [addressBig.FieldId] = new JsonObject
                                    {
                                        ["value"] = item["select_kddqvnb8"]?["value"]?.ToString(),
                                        ["label"] = item["select_kddqvnb8"]?["label"]?.ToString(),
                                    },
                                    //实际存放地
                                    [cunfang1.FieldId] = item["input_rousootb"]?.ToString(),
                                    //店铺名称
                                    [shopName.FieldId] = item["input_hdjpkhne"]?.ToString() ?? string.Empty,
                                    //店铺代码
                                    [shopCode.FieldId] = new JsonObject
                                    {
                                        ["value"] = item["select_li74i42i"]?["value"]?.ToString(),
                                        ["label"] = item["select_li74i42i"]?["label"]?.ToString(),
                                    }
                                };
                                objTui[customAssetdetails.FieldId] = dataValue;
                                dataValue.Add(new JsonObject { [customAssetList.FieldId] = query });
                                //退库配送方式 
                                objTui[customTuiKu.FieldId] = new JsonObject
                                {
                                    ["value"] = "03",
                                    ["label"] = "物流/快递",
                                };
                                //存放地大类
                                objTui[customBigcun.FieldId] = new JsonObject
                                {
                                    ["value"] = item["select_kddqvnb8"]?["value"]?.ToString(),
                                    ["label"] = item["select_kddqvnb8"]?["label"]?.ToString(),
                                };
                                //实际存放地
                                objTui[customCunFang.FieldId] = item["input_rousootb"]?.ToString();



                            }
                        }
                    }
                }

                objTui[remarks.FieldId] = "本单由调拨单号（" + order.Data["SerialNo"] + "）自动生成";
                UserDefinedForm newwtui = new UserDefinedForm();
                newwtui.FormId = vsss.Id;
                newwtui.JsonData = JsonSerializer.Serialize(objTui);
                //退库单
                if (dataValue.Count == 0)
                {
                    qwe = false;

                    dataValue.Clear();
                    objTui.Clear();
                }
                else
                {
                    //创建自定义表单
                    qwe = YideaClient.AddNewUserDefinedForm(newwtui);
                    if (qwe)
                    {
                        _logger.LogInformation("退库单生成成功");
                        dataValue.Clear();
                        objTui.Clear();

                    }
                    else
                    {
                        qwe = false;
                        dataValue.Clear();
                        objTui.Clear();
                    }
                }
            }
            return qwe;
        }
    }
}
